<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Incoming;

use App\Api\Controllers\BaseController;
use App\Exceptions\BizException;
use App\Models\ExtensionWorkers;
use App\Models\IncomingQrs;
use App\Services\Incoming\IncomingService;
use App\Services\StrorePayWaysService;
use App\Services\Vbill\IncomeResultService;
use App\Traits\ResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UploadController extends BaseController
{
    use ResponseTrait;

//    CREATE TABLE vbill_three_qrcodes (
//    id INT (11) PRIMARY KEY auto_increment,
//    store_id VARCHAR (255) NOT NULL default "",
//    store_qr VARCHAR (255) NOT NULL default "",
//    wx_qr VARCHAR (255) NOT NULL default "",
//    zfb_qr VARCHAR (255) NOT NULL default "",
//    created_at datetime NOT NULL default CURRENT_TIMESTAMP,
//    updated_at datetime NOT NULL default CURRENT_TIMESTAMP
//    ) ENGINE = INNODB charset = utf8;


    protected function qrVa(\Illuminate\Http\UploadedFile $file)
    {
        if ($file->isValid()) {
            // 获取文件相关信息
            $extension = $file->getClientOriginalExtension(); // 文件扩展名
            $filename = $file->getFilename() . "_" . time() . uniqid((string)time()) . '.' . $extension; // 新文件名
            // 保存文件
            Log::channel("upload")->info("qrVa", [$filename]);
            $file_path = $file->storeAs('/upload/images', $filename); // 保存文件到'uploads'目录
            Log::channel("upload")->info("qrVa", [$file_path]);
            //阿里云oss
            $AccessKeyId = env('ALIOSS_AccessKeyId');
            $AccessKeySecret = env('ALIOSS_AccessKeySecret');
            $endpoint = env('ALIOSS_endpoint');
            $bucket = env('ALIOSS_bucket');
            $object = $filename;
            try {
                $content = file_get_contents(public_path() . '/' . $file_path);
                $ossClient = new \OSS\OssClient($AccessKeyId, $AccessKeySecret, $endpoint);
                $data = $ossClient->putObject($bucket, $object, $content);

                $url = $data['oss-request-url'];
                //删除本地图片
                @unlink(public_path() . '/' . $file_path);
                Log::channel("upload")->info("qrVa", [public_path() . '/' . $file_path]);
                if (strpos($url, "https") === false) {
                    $url = str_replace("http", "https", $url);
                }
                return $url;
            } catch (\OSS\Core\OssException $e) {
                Log::info($e->getMessage() . ' | ' . $e->getFile() . ' | ' . $e->getLine());
            }
        }
        return "";
    }

    //门店收款码，微信认证码，支付宝认证码
    public function uploadThreeQrCode(Request $request)
    {
        $store_id = $request->post("store_id");
        $store_qr = $request->file("store_qr");
        $wx_qr = $request->file("wx_qr");
        $zfb_qr = $request->file("zfb_qr");
        $wx_qr_url = $store_qr_url = $zfb_qr_url = "";
        if (!empty($store_qr)) {
            $store_qr_url = $this->qrVa($store_qr);
        }
        if (!empty($wx_qr)) {
            $wx_qr_url = $this->qrVa($wx_qr);
        }
        if (!empty($zfb_qr)) {
            $zfb_qr_url = $this->qrVa($zfb_qr);
        }
        if (empty($store_qr_url) && empty($wx_qr_url) && empty($zfb_qr_url)) {
            return $this->errorResponse("上传失败");
        }
        //写入db
        $qr = DB::table("vbill_three_qrcodes")->where("store_id", $store_id)->first();
        if (empty($qr)) {
            DB::table("vbill_three_qrcodes")->insert([
                "store_id" => $store_id,
                "store_qr" => $store_qr_url,
                "wx_qr" => $wx_qr_url,
                "zfb_qr" => $zfb_qr_url
            ]);
        } else {
            $up = [];
            if (!empty($store_qr_url)) {
                $up["store_qr"] = $store_qr_url;
            }
            if (!empty($wx_qr_url)) {
                $up["wx_qr"] = $wx_qr_url;
            }
            if (!empty($zfb_qr_url)) {
                $up["zfb_qr"] = $zfb_qr_url;
            }
            if (!empty($up)) {
                DB::table("vbill_three_qrcodes")->where("store_id", $store_id)->update($up);
            }
        }
        return $this->successResponse("ok", true);
    }

    public function getThreeQrCode(Request $request)
    {
        $store_id = $request->get("store_id");
        $is_pc = $request->get("is_pc", 0);

        try {
            if ($is_pc == 0) {
                $type = $request->get("type");
                if (empty($store_id) || !in_array($type, ["store_qr", "wx_qr", "zfb_qr"])) {
                    throw new BizException("参数异常");
                }
                list($isok, $error) = (new IncomeResultService())->query($store_id);
                //进件查询
                switch ($type) {
                    case "store_qr":
                        break;
                    case "wx_qr":
                    case "zfb_qr":
                        if ($isok == false) {
                            throw new BizException($error);
                        }
                        break;
                }
            }
            $qr = DB::table("vbill_three_qrcodes")->where("store_id", $store_id)->first();
            return $this->successResponse("ok", [
                "store_qr" =>  empty($qr) ? "" : $qr->store_qr,
                "wx_qr" => empty($qr) ? "" : $qr->wx_qr,
                "zfb_qr" => empty($qr) ? "" : $qr->zfb_qr
            ]);
        } catch (\Throwable $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    public function upload(Request $request)
    {
        try {
            //需要识别码
            //需要随机码
            $user = $this->parseToken();
            $worker = ExtensionWorkers::query()->where([
                "phone" => $user->worker_phone
            ])->first();

            if (empty($worker)) {
                throw new \Exception("推广人员不存在");
            }

            $type = $request->get('type', 'store');
            $img_type = $request->get('img_type', '');
//            dump($img_type);die;
            $file_type = $request->get('file_type', 'img'); //img file

            if ($file_type == "img") {
                //上传图片具体操作
                $file_name = $_FILES['img_upload']['name'];
                $file_type = $_FILES["img_upload"]["type"];
                $file_tmp = $_FILES["img_upload"]["tmp_name"];
                $file_error = $_FILES["img_upload"]["error"];
                $file_size = $_FILES["img_upload"]["size"];
            } else {
                //上传文件具体操作
                $file_name = $_FILES['file']['name'];
                $file_type = $_FILES["file"]["type"];
                $file_tmp = $_FILES["file"]["tmp_name"];
                $file_error = $_FILES["file"]["error"];
                $file_size = $_FILES["file"]["size"];
            }
            if ($file_error > 0) { // 出错
                return $this->errorResponse($file_error);
            }
            if ($file_size > 50485769999) { // 文件太大了
                return $this->errorResponse("上传文件过大");
            }
            $file_name_arr = explode('.', $file_name);
            //域名授权目录提交
            //域名授权目录提交
            $new_file_name = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)) . "." . $file_name_arr[1];//编号

            if (!in_array(strtolower($file_name_arr[1]), ['jpg', 'png', 'gif', 'jpeg', 'pem', 'mp4', 'key', 'txt'])) {
                return $this->errorResponse("格式不支持");
            }
            $file_path = "/upload/images/" . $new_file_name;
            if ($type == 'wxfile') {
                $file_path = "/upload/images/" . $new_file_name;
            }
            //域名授权目录提交
            if ($type == 'wxauth') {
                $file_path = "/" . $new_file_name;
            }
            if ($type == "store") {
                $file_path = "/upload/images/" . $new_file_name;
            }
            if (file_exists($file_path)) {
                return $this->errorResponse("文件已存在");
            } else {
                $upload_result = move_uploaded_file($file_tmp, public_path() . $file_path); // 此函数只支持 HTTP POST 上传的文件
                if ($upload_result) {
                    $url = url($file_path);
                    if ($type == 'wxfile') {
                        $url = $file_path;
                    }
                    $oss = 1;
                    if ($oss && env('ALIOSS_AccessKeyId')) {
                        //阿里云oss
                        $AccessKeyId = env('ALIOSS_AccessKeyId');
                        $AccessKeySecret = env('ALIOSS_AccessKeySecret');
                        $endpoint = env('ALIOSS_endpoint');
                        $bucket = env('ALIOSS_bucket');

                        $object = $new_file_name;
                        try {
                            $content = file_get_contents(public_path() . $file_path);
                            $ossClient = new \OSS\OssClient($AccessKeyId, $AccessKeySecret, $endpoint);
                            $ossClient->setUseSSL(true);
                            $data = $ossClient->putObject($bucket, $object, $content);
                            Log::info('阿里云OSS结果');
                            $url = $data['oss-request-url'];
                            //删除本地图片
                            // $unlink = unlink(public_path() . $file_path);
                        } catch (\OSS\Core\OssException $e) {
                            Log::info($e->getMessage() . ' | ' . $e->getFile() . ' | ' . $e->getLine());
                        }
                    }
                    //识别营业执照
                    $baseQueryUploadController = new \App\Api\Controllers\Basequery\UploadController();
                    $is_yyzz = 1;
                    if ($is_yyzz && $img_type == '1') {
                        // print_r($url);die;
                        $data_return['store_license_no'] = '';
                        $data_return['store_license_time'] = '';
                        $data_return['store_license_stime'] = '';
                        $data_return['is_long_time'] = '0';
                        date_default_timezone_set("GMT");
                        $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                        $array = [
                            'Action' => 'RecognizeBusinessLicense',
                            'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                            'SignatureMethod' => 'HMAC-SHA1',
                            'SignatureVersion' => '1.0',
                            'SignatureNonce' => time(),
                            'Timestamp' => date('Y-m-d\TH:i:s\Z', time()),
                            'Version' => '2021-07-07',
                            'Format' => 'JSON',
                            'Url' => $url
                        ];
                        $str = $baseQueryUploadController->getSignContent($array);
                        $stringToSign = 'GET&%2F&' . $baseQueryUploadController->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                        $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                        $array['Signature'] = $signature;
                        $urls = $urls . http_build_query($array);
                        $result = $baseQueryUploadController->https_request1($urls);
                        $result = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
                        // print_r($result);die;
                        error_log(date('Y-m-d H:i:s') . " 【阿里云oss】： " . json_encode($result) . "\n\n", 3, "/tmp/" . 'oss' . date('Ymd') . ".log");

                        $uploadRet = json_decode($result['Data'], true);

                        // dump($uploadRet);die;
                        if (isset($uploadRet['data'])) {
                            $data_return['store_license_no'] = $uploadRet['data']['creditCode']; // 营业执照编号

                            $store_license_stime = $uploadRet['data']['RegistrationDate'];

                            $store_license_stime = str_replace("年", "-", $store_license_stime);
                            $store_license_stime = str_replace("月", "-", $store_license_stime);
                            $store_license_stime = str_replace("日", "", $store_license_stime);
                            $data_return['store_license_stime'] = $store_license_stime;
//                                dump($store_license_stime);die;
                            $store_license_time = $uploadRet['data']['validPeriod'];
                            $store_license_time = str_replace("年", "-", $store_license_time);
                            $store_license_time = str_replace("月", "-", $store_license_time);
                            $store_license_time = str_replace("日", "", $store_license_time);
                            $data_return['store_license_time'] = $store_license_time;
                            if ($data_return['store_license_time'] == "/长期") {
                                // $data_return['is_long_time'] = '1';
                                $data_return['store_license_time'] = '2099-12-01';
                            }
                        }
                    }

                    //
                    $is_card_a = 1;
                    if ($is_card_a && $img_type == '2') {
                        $data_return['sfz_name'] = '';
                        $data_return['sfz_no'] = '';
                        try {
                            // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用
                            date_default_timezone_set("GMT");
                            $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                            $array = array(
                                'Action' => 'RecognizeIdcard',
                                'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                                'SignatureMethod' => 'HMAC-SHA1',
                                'SignatureVersion' => '1.0',
                                'SignatureNonce' => time(),
                                'Timestamp' => date('Y-m-d\TH:i:s\Z', time()),
                                'Version' => '2021-07-07',
                                'Format' => 'JSON',
                                'Url' => $url
                            );
                            $str = $baseQueryUploadController->getSignContent($array);
                            $stringToSign = 'GET&%2F&' . $baseQueryUploadController->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                            $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                            $array['Signature'] = $signature;
                            $urls = $urls . http_build_query($array);
                            $result = $baseQueryUploadController->https_request1($urls);
                            $result = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
                            $uploadRet = json_decode($result['Data'], true);

                            if (isset($uploadRet['data']['face']['data'])) {
                                if (isset($uploadRet['data']['face']['data']['name'])) {
                                    $data_return['sfz_name'] = $uploadRet['data']['face']['data']['name']; // 身份证名字
                                }
                                if (isset($uploadRet['data']['face']['data']['idNumber'])) {
                                    $data_return['sfz_no'] = $uploadRet['data']['face']['data']['idNumber']; // 身份证号码
                                }
                            }
                        } catch (\Exception $exception) {

                        }
                    }

                    //识别身份证反面
                    $is_card_b = 1;
                    if ($is_card_b && $img_type == '3') {
                        $data_return['sfz_time'] = '';
                        $data_return['sfz_stime'] = '';

                        try {
                            date_default_timezone_set("GMT");
                            $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                            $array = array(
                                'Action' => 'RecognizeIdcard',
                                'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                                'SignatureMethod' => 'HMAC-SHA1',
                                'SignatureVersion' => '1.0',
                                'SignatureNonce' => time(),
                                'Timestamp' => date('Y-m-d\TH:i:s\Z', time()),
                                'Version' => '2021-07-07',
                                'Format' => 'JSON',
                                'Url' => $url
                            );
                            $str = $baseQueryUploadController->getSignContent($array);
                            $stringToSign = 'GET&%2F&' . $baseQueryUploadController->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                            $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                            $array['Signature'] = $signature;
                            $urls = $urls . http_build_query($array);
                            $result = $baseQueryUploadController->https_request1($urls);
                            $result = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
                            $uploadRet = json_decode($result['Data'], true);
//                            dump($uploadRet);die; // 2018.09.30-2038.09.30
//                            dump(2);die;
                            if (isset($uploadRet['data']['back']['data']['validPeriod'])) {
//                                if (isset($uploadRet['valid_date'])) {
                                $valid_date = explode("-", $uploadRet['data']['back']['data']['validPeriod']);
//                                    dump($valid_date);die;
                                if (isset($valid_date[0])) {
                                    $data_return['sfz_stime'] = $valid_date[0];
                                    $data_return['sfz_stime'] = str_replace(".", "-", $data_return['sfz_stime']);
                                }
                                if (isset($valid_date[1])) {
                                    $data_return['sfz_time'] = $valid_date[1];
                                    $data_return['sfz_time'] = str_replace(".", "-", $data_return['sfz_time']);
                                }
                            }
                        } catch (\Exception $exception) {
                        }
                    }

                    //识别银行卡正面
                    $is_bank_a = 1;
                    if ($is_bank_a && $img_type == '4') {
                        $data_return['store_bank_no'] = '';
                        $data_return['bank_name'] = '';

                        try {
                            date_default_timezone_set("GMT");
                            $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                            $array = array(
                                'Action' => 'RecognizeBankCard',
                                'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                                'SignatureMethod' => 'HMAC-SHA1',
                                'SignatureVersion' => '1.0',
                                'SignatureNonce' => time(),
                                'Timestamp' => date('Y-m-d\TH:i:s\Z', time()),
                                'Version' => '2021-07-07',
                                'Format' => 'JSON',
                                'Url' => $url
                            );
                            $str = $baseQueryUploadController->getSignContent($array);
                            $stringToSign = 'GET&%2F&' . $baseQueryUploadController->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                            $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                            $array['Signature'] = $signature;
                            $urls = $urls . http_build_query($array);
                            $result = $baseQueryUploadController->https_request1($urls);
                            $result = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
                            $uploadRet = json_decode($result['Data'], true);
                            if (isset($uploadRet['data'])) {
                                $data_return['store_bank_no'] = $uploadRet['data']['cardNumber'];
                                $data_return['bank_name'] = $uploadRet['data']['bankName'];
                            }
                        } catch (\Exception $exception) {

                        }
                    }
                    $data_return['img_url'] = $url;
                    return $this->successResponse("ok", ["data" => $data_return]);
                } else {
                    return $this->errorResponse("系统错误重新上传");
                }
            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getLine(),
            ]);
        }
    }
}